import React, { useEffect, useState } from "react";
import { Button, Divider, message, Pagination, Space, Table } from "antd";
import { ChangeEditorApi, EditorApi } from "request/api";

export default function NameList() {
  const [listData, setListData] = useState<any[]>([]);
  const [num, setNum] = useState(0);
  const columns = [
    {
      title: "头像",
      dataIndex: "avatar",
    },
    {
      title: "姓名",
      dataIndex: "username",
    },
    {
      title: "角色",
      dataIndex: "player",
    },
    {
      title: "编辑权限",
      dataIndex: "editable",
    },
    {
      title: "操作",
      dataIndex: "action",
    },
  ];

  //开通编辑权限
  const openEditable = (id: number) => {
    ChangeEditorApi({
      id,
      open: 1,
    }).then((res: any) => {
      console.log(res);
      if (res.errCode === 0) {
        message.success(res.message);
        setNum(num + 1);
      } else {
        message.error(res.message);
      }
    });
  };

  //取消编辑权限
  const closeEditable = (id: number) => {
    ChangeEditorApi({
      id,
      open: 0,
    }).then((res: any) => {
      console.log(res);
      if (res.errCode === 0) {
        message.success(res.message);
        setNum(num + 1);
      } else {
        message.error(res.message);
      }
    });
  };
  useEffect(() => {
    //获取用户列表
    EditorApi().then((res: any) => {
      console.log(res);

      let newArr: any[] = [];
      if (res.errCode === 0) {
        message.success(res.message);
        res.data.forEach((item: any) => {
          let obj = {
            key: item.id,
            avatar: (
              <img
                width='40'
                height='40'
                style={{ borderRadius: "50%" }}
                src={process.env.SERVER_HOST_PORT + "/" + item.avatar}
                alt='头像'
              />
            ),
            username: item.username,
            player: item.player === "vip" ? "管理员" : "编辑人员",
            editable: item.editable === 1 ? "已开通" : "未开通",
            action: (
              <>
                <Space split={<Divider type='vertical' />}>
                  <Button type='primary' onClick={() => openEditable(item.id)}>
                    开通编辑权限
                  </Button>

                  <Button
                    type='primary'
                    onClick={() => closeEditable(item.id)}
                    danger
                  >
                    取消编辑权限
                  </Button>
                </Space>
              </>
            ),
          };
          newArr.push(obj);
        });
        setListData(newArr);
      } else {
        message.error(res.message);
      }
    });
  }, [num]);

  return (
    <div>
      <Table columns={columns} dataSource={listData} pagination={false} />
    </div>
  );
}
